#!/usr/local/bin/python3
# -*- coding: utf-8 -*-

"""
@File    : api统一响应结构.py
@Author  : lepal
@Time    : 2024-08-21 10:27
"""

from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, Integer, String

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
db = SQLAlchemy(app)

# 定义模型
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    email = db.Column(db.String(100))

# 创建数据库表
db.create_all()

# 辅助函数: 将模型对象转换为字典
def object_as_dict(obj):
    return {c.name: getattr(obj, c.name) for c in obj.__table__.columns}

# 辅助函数: 将多个模型对象转换为字典列表
def objects_as_dict_list(objects):
    return [object_as_dict(obj) for obj in objects]

# 定义 Response 类
class APIResponse:
    def __init__(self, status, message, data=None, errors=None):
        self.status = status
        self.message = message
        self.data = data
        self.errors = errors

    def to_dict(self):
        return {
            "status": self.status,
            "message": self.message,
            "data": self.data,
            "errors": self.errors
        }

    @classmethod
    def success(cls, data=None, message="Success"):
        """创建一个成功的响应对象"""
        return cls("success", message, data)

    @classmethod
    def failure(cls, message="Failure"):
        """创建一个失败的响应对象"""
        return cls("failure", message)

    @classmethod
    def error(cls, errors, message="Error occurred"):
        """创建一个错误的响应对象"""
        return cls("error", message, errors=errors)

# API 路由
@app.route('/users', methods=['GET'])
def get_users():
    response = None
    try:
        users = User.query.all()
        data = objects_as_dict_list(users)
        response = APIResponse.success(data, "Users fetched successfully.")
    except Exception as e:
        response = APIResponse.error(str(e), "Failed to fetch users.")
    finally:
        return jsonify(response.to_dict())

# 主程序
if __name__ == '__main__':
    app.run(debug=True)